package com.ly.controller;


import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ly.base.ResponseData;
import com.ly.dto.PassDto;
import com.ly.entity.SysRole;
import com.ly.entity.SysUser;
import com.ly.entity.SysUserRole;
import com.ly.lang.Const;
import com.ly.param.UserParam;
import com.ly.utils.DateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  用户管理
 * </p>
 *
 * @author gwq
 * @since 2022-06-07
 */
@Api(tags = "用户管理")
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends BaseController {

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @ApiOperation(value="用户信息")
    @PreAuthorize("hasAnyAuthority('sys:user:list')")
    @GetMapping("/info/{id}")
    public ResponseData info(@PathVariable("id") String id){
        SysUser sysUser = sysUserService.getById(id);
        Assert.notNull(sysUser, "找不到该管理员");

        List<SysRole> sysRoles = sysRoleService.listRolesByUserId(id);
        sysUser.setSysRoles(sysRoles);

        return ResponseData.success("查询成功！",sysUser);
    }

    @ApiOperation(value="用户列表")
    @GetMapping("/list")
    @PreAuthorize("hasAnyAuthority('sys:user:list')")
    public ResponseData list(UserParam userParam){
        Page<SysUser> pageData =  sysUserService.pageUser(userParam);
        pageData.getRecords().forEach(u -> {
            u.setSysRoles(sysRoleService.listRolesByUserId(u.getId()));
        });
        return ResponseData.success("查询成功！",pageData);
    }

    @ApiOperation(value="新增")
    @PreAuthorize("hasAnyAuthority('sys:user:save')")
    @PostMapping("/save")
    public ResponseData save(@Validated @RequestBody SysUser sysUser, Principal principal){

        SysUser sysUser1 = sysUserService.getByUserName(principal.getName());
        if(sysUser1!=null) {
            sysUser.setCreatedBy(sysUser1.getId());
            sysUser.setCreatedAt(DateUtils.getYyyyMMddHHmmss(new Date()));
        }
        //默认头像
        sysUser.setAvatar(Const.DEFULT_AVATAR);

        // 默认密码
        String password = bCryptPasswordEncoder.encode(Const.DEFFULT_PASSWORD);

        sysUser.setPassword(password);
        sysUserService.save(sysUser);

        return ResponseData.success("新增成功！",sysUser);
    }

    @ApiOperation(value="修改")
    @PreAuthorize("hasAnyAuthority('sys:user:update')")
    @PostMapping("/update")
    public ResponseData update(@Validated @RequestBody SysUser sysUser, Principal principal){
        SysUser sysUser1 = sysUserService.getByUserName(principal.getName());
        if(sysUser1!=null) {
            sysUser.setUpdatedBy(sysUser1.getId());
            sysUser.setUpdatedAt(DateUtils.getYyyyMMddHHmmss(new Date()));
        }
        sysUserService.updateById(sysUser);
        return ResponseData.success("修改成功！",sysUser);
    }

    @ApiOperation(value = "充值金额")
    @PostMapping("/cz")
    public ResponseData cz(@RequestBody SysUser sysUser,Principal principal){

        SysUser sysUser2 = sysUserService.getByUserName(principal.getName());

        SysUser sysUser1 = sysUserService.getById(sysUser.getId());
        if(sysUser1!=null){

            SysRole sysRole = sysRoleService.getUserIdRole(sysUser1.getId());
            if(sysRole.getCode().equalsIgnoreCase("admin")){
                return ResponseData.fail("管理员不能充值！");
            }

            sysUser1.setUpdatedBy(sysUser2.getId());
            sysUser1.setUpdatedAt(DateUtils.getYyyyMMddHHmmss(new Date()));
            if(sysUser1.getBalance()!=null){
                sysUser1.setBalance(sysUser1.getBalance()+sysUser.getBalance());
            }else {
                sysUser1.setBalance(sysUser.getBalance());
            }
        }
        sysUserService.updateById(sysUser1);
        return ResponseData.success("充值成功！");
    }

    @ApiOperation(value="批量删除")
    @Transactional
    @PreAuthorize("hasAnyAuthority('sys:user:delete')")
    @PostMapping("/delete")
    public ResponseData delete(@RequestBody String[] ids){
        sysUserService.removeByIds(Arrays.asList(ids));
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().in("user_id", ids));
        return ResponseData.success("删除成功！",true);
    }

    @ApiOperation(value="分配用户角色")
    @PreAuthorize("hasAnyAuthority('sys:user:role')")
    @Transactional
    @PostMapping("/role/{userId}")
    public ResponseData rolePerm(@PathVariable("userId") String userId, @RequestBody String[] roleIds){
        ArrayList<SysUserRole> sysUserRoles = new ArrayList<>();
        Arrays.asList(roleIds).stream().forEach(r ->{
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(r);
            sysUserRole.setUserId(userId);
            sysUserRoles.add(sysUserRole);
        });
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().eq("user_id", userId));
        sysUserRoleService.saveBatch(sysUserRoles);
        // 删除缓存
        SysUser byId = sysUserService.getById(userId);
        sysUserService.clearUserAuthorityInfo(byId.getUserName());
        return ResponseData.success("分配成功！",true);
    }

    @ApiOperation(value="重置")
    @PreAuthorize("hasAnyAuthority('sys:user:repass')")
    @PostMapping("/repass")
    public ResponseData repass(@RequestBody String userId, Principal principal){

        SysUser sysUser = sysUserService.getById(userId);

        SysUser sysUser1 = sysUserService.getByUserName(principal.getName());
        if(sysUser1!=null) {
            sysUser.setUpdatedBy(sysUser1.getId());
            sysUser.setUpdatedAt(DateUtils.getYyyyMMddHHmmss(new Date()));
        }
        sysUser.setPassword(bCryptPasswordEncoder.encode(Const.DEFFULT_PASSWORD));
        sysUserService.updateById(sysUser);

        return ResponseData.success("重置成功!",true);
    }

    @ApiOperation(value="修改密码")
    @Transactional
    @PostMapping("/updatePass")
    public ResponseData repass(@Validated @RequestBody PassDto passDto, Principal principal){

        SysUser sysUser = sysUserService.getByUserName(principal.getName());

        boolean matches = bCryptPasswordEncoder.matches(passDto.getCurrentPass(), sysUser.getPassword());
        if(!matches){
            return ResponseData.fail("旧密码不正确");
        }
        sysUser.setPassword(bCryptPasswordEncoder.encode(passDto.getPassword()));
        sysUserService.updateById(sysUser);

        return ResponseData.success("修改成功!",true);
    }


    @ApiOperation(value="加入会员")
    @PostMapping("/member")
    public ResponseData member(@RequestBody String userId, Principal principal){

        SysUser sysUser = sysUserService.getById(userId);

        if(sysUser.getBalance()==null||sysUser.getBalance()-10<0){
            return ResponseData.fail("余额不足请联系管理员充值！");
        }
        sysUser.setBalance(sysUser.getBalance()-10);


        ArrayList<SysUserRole> sysUserRoles = new ArrayList<>();

        SysRole sysRole = sysRoleService.getByCode("h001");


        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setRoleId(sysRole.getId());
        sysUserRole.setUserId(userId);

        sysUserRoles.add(sysUserRole);

        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().eq("user_id", userId));
        sysUserRoleService.saveBatch(sysUserRoles);
        // 删除缓存
        SysUser byId = sysUserService.getById(userId);
        sysUserService.clearUserAuthorityInfo(byId.getUserName());

        sysUserService.updateById(sysUser);

        return ResponseData.success("加入成功！",true);

    }


}
